<?php
namespace App\Repositories;

use App\Models\Search;
use App\Models\SearchTotal;

class SearchRepository
{

    /**
     * @param $query
     * @param $tag
     * @return mixed
     */
    public function search($query, $tag)
    {
        $data = Search::whereIn('key', $this->explodeWord($query))->where('tag', $tag)->get();
        $maxLength = 0;
        $maxLengthIndex = null;
        $data->each(function ($item, $index) use (&$maxLength, &$maxLengthIndex){
            if (mb_strlen($item['key']) > $maxLength) {
                $maxLength = mb_strlen($item['key']);
                $maxLengthIndex = $index;
            }
        });

        $result = $maxLengthIndex !== null ? $data->get($maxLengthIndex) : null;
        $this->logging($query, !empty($result));
        return $result;
    }


    /**
     * 分割字多种组合
     *
     * @param $string
     * @return array
     */
    public function explodeWord($string)
    {
        $words = [];
        preg_match_all('/./u', $string, $matches);
        foreach ($matches[0] as $key => $word) {
            $words[] = $word;
            foreach (array_slice($matches[0], $key + 1) as $word2) {
                $words[] = last($words) . $word2;
            }
        }
        return $words;
    }

    /**
     * 记录搜索词
     *
     * @param string $word
     * @param bool $hasReturned
     */
    public function logging($word, $hasReturned = false)
    {
        SearchTotal::create([
            'word' => $word,
            'user_id' => request()->user()->id,
            'has_returned' => $hasReturned
        ]);
    }
}